package com.example.dealdata.service.chengyu;

import com.example.dealdata.dao.chengyu.ChengyuJLKeyDao;
import com.example.dealdata.dao.chengyu.Chengyu_JL_listDao;
import com.example.dealdata.pojo.chengyu.Chengyu_JL_Key;
import com.example.dealdata.pojo.chengyu.Chengyu_JL_list;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ChengyuService {
    @Autowired
    private ChengyuJLKeyDao chengyuJLKeyDao;
    @Autowired
    private Chengyu_JL_listDao chengyu_jl_listDao;

    public List<Chengyu_JL_Key> findByFKey(String fKey){
//        return chengyuJLKeyDao.findAll();
        return chengyuJLKeyDao.findByfkey(fKey);
    }

    public List<Chengyu_JL_Key> findGroupByfkey(){
        return chengyuJLKeyDao.findGroupByfkey();
    }

    public String creatJLData(){
        //1.缓存数据到内存到map中 用成语首字的拼音作为key，该key对应的成语list为value
        Map<String,List<Chengyu_JL_Key>> map = new HashMap<String,List<Chengyu_JL_Key>>();
        List<Chengyu_JL_Key> keylist = this.findGroupByfkey();
        if(keylist==null || keylist.size()==0) return "fail";
        for (Chengyu_JL_Key e:keylist) {
            List<Chengyu_JL_Key> l = chengyuJLKeyDao.findVialCy(e.getFkey());//通过fkey查找所有成语
            map.put(e.getFkey(),l);
        }

        //2.插入接龙数据
        List<Chengyu_JL_Key> cylist = chengyuJLKeyDao.findAll();
        if(cylist!=null && cylist.size()>0){
            for (Chengyu_JL_Key e : cylist) {
                //1.插入龙头数据
                Chengyu_JL_list jl = new Chengyu_JL_list();
                jl.setId(UUID.randomUUID().toString());
                jl.setChengyu(e.getName());
                jl.setChengyuid(e);
                jl.setLtchengyuid(e.getInfoid());
                jl.setDisplayorder(1);//龙头成语为1
                chengyu_jl_listDao.save(jl);

                for(int i=2;i<11;i++){
                    List<Chengyu_JL_Key> tmp = map.get(jl.getChengyuid().getLkey());//用成语的最后一个字的拼音作为key去内存中检查内容
                    if(tmp==null||tmp.size()==0) break;//没有找到接龙就中断
                    System.out.println(jl.getChengyuid().getLkey() + ".size="+tmp.size());
                    Chengyu_JL_Key sjcy = tmp.get(new Random().nextInt(tmp.size()));//随机一个成语
                    jl.setId(UUID.randomUUID().toString());
                    jl.setChengyu(sjcy.getName());
                    jl.setChengyuid(sjcy);
                    jl.setDisplayorder(i);
                    chengyu_jl_listDao.save(jl);
                }
            }
        }

        return "succ";
    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            System.out.println(new Random().nextInt(1));
        }
    }
}
